﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Vit.Web.Models;

namespace Vit.AdminModule.Areas.Admin.Providers
{
    public class SqlTrackProvider : Vit.Web.Providers.ITrackProvider
    {
        private WebProvidersDb db = new WebProvidersDb();

        #region ITrackProvider Members

        public Track GetTrack(string objectType, string objectId)
        {
            var track = db.Tracks.FirstOrDefault(o => o.ObjectType == objectType && o.ObjectId == objectId);
            if (track == null)
            {
                track = new Track()
                {
                    ObjectType = objectType,
                    ObjectId = objectId
                };

                db.Tracks.Add(track);
                db.SaveChanges();
            }
            return track;
        }

        public void Track(string objectType, string objectId, int visit, int hit, int favorate, int mark)
        {
            var track = db.Tracks.FirstOrDefault(o => o.ObjectType == objectType && o.ObjectId == objectId);
            if (track == null)
            {
                track = new Track()
                {
                    ObjectType = objectType,
                    ObjectId = objectId,
                    Favorates = favorate,
                    Marks = mark,
                    Hits = hit,
                    Visits = visit
                };

                db.Tracks.Add(track);
                db.SaveChanges();
            }
            else
            {
                track.Favorates += favorate;
                track.Marks += mark;
                track.Hits += hit;
                track.Visits += visit;

                db.SaveChanges();
            }
        }

        #endregion

        #region IProvider Members

        public string Name
        {
            get { return "SqlTrackProvider"; }
        }

        #endregion
    }
}